<template>
  <div>
    <div class="card-add">
      <footer>
        <mt-button @click.native="save">保存</mt-button>
      </footer>
      <!-- 选择银行 -->
      <mt-field label="银行：" placeholder="点击选择" readonly @click.native="showPopup" v-model="bank_name">
        <img src="/src/assets/icons/add.png">
      </mt-field>
      <mt-popup v-model="bankPopup" position="right">
        <div class="title">
          <span>{{bankTitle}}</span>
          <img src="/src/assets/icons/set.png" @click="setBank" v-show="!ifSet">
          <span class="blue-text" @click="completeBank" v-show="ifSet">完成</span>
        </div>
        <div class="block" v-for="(v, k) in bankList" :key="k">
          <div class="letter">{{k}}</div>
          <div class="flex-box">
            <div class="item" 
              :class="{active: bank_id === b.id, edit: ifSet && b.id > 100}" 
              v-for="b in v" :key="b.id" 
              @click="!ifSet && bankChoose(b.id, b.name)"
            >
              {{b.name}}
              <img src="/src/assets/icons/delete-circle.png" class="delete" @click.stop="deleteBank(b.id)">
            </div>
            <div class="item" v-if="v.length % 3 === 2"></div>
          </div>
        </div>
        <div class="block">
          <div class="letter">其他</div>
          <mt-field label="" placeholder="点击输入" v-model="custom">
            <img class="big" src="/src/assets/icons/add-green.png" @click="saveCustom">
          </mt-field>
        </div>
      </mt-popup>
      
      <!-- 卡种 -->
      <mt-field label="卡种：" placeholder="信用卡类型" readonly v-model="card_type" @click.native="showType">
        <img src="/src/assets/icons/add.png">
      </mt-field>
      <mt-popup v-model="typePopup" position="right">
        <div class="title">选择银行卡卡种</div>
        <div class="block" v-for="(list, k) in cardTypeList" :key="k">
          <div class="letter">{{k}}</div>
          <div class="flex-box">
            <div class="item" 
              v-for="v in list" :key="v.id"
              @click="cardChoose(v.id, v.card_name)"
              :class="{active: card_type === v.card_name}"
            >
              {{v.card_name}}
            </div>
            <div class="item" v-if="list.length % 3 === 2"></div>
          </div>
        </div>
        <div class="block">
          <div class="letter">自定义卡种</div>
          <mt-field label="" placeholder="点击输入" v-model="card_type">
            <img class="big" src="/src/assets/icons/add-green.png" @click="saveCardType">
          </mt-field>
        </div>
      </mt-popup>

      <!-- 持卡人 -->
      <mt-field label="持卡人：" placeholder="持卡人" readonly v-model="card_owner" @click.native="showOwner">
        <img src="/src/assets/icons/add.png">
      </mt-field>
      <mt-popup v-model="ownerPopup" position="right">
        <div class="title">
          <span>{{ownerTitle}}</span>
          <img src="/src/assets/icons/set.png" @click="setOwner" v-show="!ifSet">
          <span class="blue-text" @click="completeOwner" v-show="ifSet">完成</span>
        </div>
        <div class="block">
          <div class="letter"></div>
          <div class="flex-box">
            <div class="item" 
              v-for="(v, k) in ownerList" :key="k" 
              @click="!ifSet && ownerChoose(v.id, v.owner)"
              :class="{active: card_owner_id === v.id, edit: card_owner_id !== v.id && v.id !== 0 && ifSet}"
            >
              {{v.owner}}
              <img src="/src/assets/icons/delete-circle.png" class="delete" @click.stop="deleteOwner(v.id)">
            </div>
            <div class="item" v-if="ownerList.length % 3 === 2"></div>
          </div>
        </div>
        <div class="block">
          <div class="letter">新增持卡人</div>
          <mt-field label="" placeholder="点击输入" v-model="ownerName">
            <img class="big" src="/src/assets/icons/add-green.png" @click="saveOwner">
          </mt-field>
        </div>
      </mt-popup>

      <!-- 卡号 -->
      <mt-field label="卡号后四位：" placeholder="点击输入" v-model="card_no"></mt-field>

      <!-- 额度 -->
      <mt-field label="额度(元)：" placeholder="点击输入" v-model="credit_amount"></mt-field>

      <!-- 账单日 -->
      <div class="pos-r">
        <mt-field label="销账单日：" placeholder="点击选择" v-model="statement_day_text" readonly @click.native="statementDate">
          <img src="/src/assets/icons/calendar.png">
        </mt-field>
        <img src="/src/assets/icons/help-blue.png" class="helper" @click="billAlert" style="left: 80px;">
      </div>
      <mt-datetime-picker 
        ref="statement_day" 
        type="date" 
        class="only-day" 
        year-format="{value} 年" 
        month-format="{value} 月" 
        date-format="{value} 日" 
        v-model="statement_day_picker">
      </mt-datetime-picker>

      <!-- 还款期 -->
      <div class="pos-r">
        <mt-field label="还款日-账单日：" placeholder="点击输入" v-model="payment_day"></mt-field>
        <img src="/src/assets/icons/help-blue.png" class="helper" @click="repayAlert">
      </div>

      <!-- 年费缴纳 -->
      <div class="pos-r">
        <mt-field label="年费缴纳日：" placeholder="点击选择" v-model="annual_fee_date_text" readonly @click.native="showPicker">
          <img src="/src/assets/icons/calendar.png">
        </mt-field>
        <img src="/src/assets/icons/help-blue.png" class="helper" @click="feeAlert" style="left: 90px;">
      </div>
      <mt-datetime-picker 
        ref="fee_date" 
        type="date" 
        class="month-day" 
        year-format="{value} 年" 
        month-format="{value} 月" 
        date-format="{value} 日" 
        v-model="annual_fee_date_picker">
      </mt-datetime-picker>
      
      <!-- 年费规则 -->
      <mt-field label="年费规则：" placeholder="点击选择" :value="ruleText" readonly @click.native="showRule"></mt-field>
      <mt-popup v-model="rulePopup" position="right">
        <div class="title">选择年费抵扣规则</div>
        <div class="block pos-r">
          <div class="letter"></div>
          <mt-radio align="right" v-model="feeRule" :options="radioOptions"></mt-radio>
          <div class="radio-input-row">
            <input type="text" class="mint-field-core radio-input" @focus="radioFocus('3')" v-model="swing_times" placeholder="填写刷卡笔数">
            <input type="text" class="mint-field-core radio-input" @focus="radioFocus('4')" v-model="consume_amount" placeholder="填写刷卡金额">
            <input type="text" class="mint-field-core radio-input" @focus="radioFocus('5')" v-model="point_fee" placeholder="填写所需积分">
            <input type="text" class="mint-field-core radio-input" @focus="radioFocus('6')" v-model="cash_payment" placeholder="填写所需金额">
            <input type="text" class="mint-field-core radio-input" @focus="radioFocus('1')" readonly>
            <input type="text" class="mint-field-core radio-input" @focus="radioFocus('2')" readonly>
          </div>
        </div>
      </mt-popup>
    </div>
  </div>
</template>

<script>
  import {MessageBox, Toast} from 'Mint-ui'

  export default {
    name: 'AddNewCard',
    data () {
      return {
        bankPopup: false,
        typePopup: false,
        ownerPopup: false,
        rulePopup: false,
        radioOptions: [
          {label: '刷卡减免：', value: '3'},
          {label: '刷满减免：', value: '4'},
          {label: '积分抵扣：', value: '5'},
          {label: '现金缴纳：', value: '6'},
          {label: '有效期免：', value: '1'},
          {label: '终身减免：', value: '2'}
        ],
        bankList: [],
        cardTypeList: [],
        /* 银行修改 */
        custom: '',
        bankTitle: '选择银行',
        customBank: [],
        /* 持卡人 */
        ownerList: [],
        ownerName: '',
        ownerTitle: '选择持卡人',
        ifSet: false,
        /* 卡片信息 */
        bank_id: '',
        bank_name: '',
        card_type: '',
        card_no: '',
        card_owner: '本人',
        card_owner_id: 0,
        credit_amount: '',
        statement_day: '',
        statement_day_picker: '',
        statement_day_text: '',
        payment_day: '',
        annual_fee_date: '',
        annual_fee_date_picker: '',
        annual_fee_date_text: '',
        feeRule: '0',
        feeRuleValue: '',
        swing_times: '',
        consume_amount: '',
        point_fee: '',
        cash_payment: '',
        card_id: this.$route.params.id || 0
      }
    },
    watch: {
      annual_fee_date_picker (v) {
        this.annual_fee_date = `${v.getMonth() + 1}/${v.getDate()}`
        this.annual_fee_date_text = `每年${v.getMonth() + 1}月${v.getDate()}日`
      },
      statement_day_picker (v) {
        this.statement_day = v.getDate()
        this.statement_day_text = `每月${v.getDate()}日`
      },
      swing_times (v) {
        if (isNaN(Number(v))) {
          msg('请填写数字')
          this.swing_times = ''
        }
      },
      consume_amount (v) {
        if (isNaN(Number(v))) {
          msg('请填写数字')
          this.consume_amount = ''
        }
      },
      point_fee (v) {
        if (isNaN(Number(v))) {
          msg('请填写数字')
          this.point_fee = ''
        }
      },
      cash_payment (v) {
        if (isNaN(Number(v))) {
          msg('请填写数字')
          this.cash_payment = ''
        }
      }
    },
    computed: {
      // v-model绑定，计算属性必须设置set,不然报错，v-bind没有此项（自己理解不一定准确）
      ruleText () {
        switch (this.feeRule) {
          case '1':
            return `有效期免`
          case '2':
            return `终身减免`
          case '3':
            this.feeRuleValue = this.swing_times
            return `刷${this.swing_times}笔免`
          case '4':
            this.feeRuleValue = this.consume_amount
            return `刷${this.consume_amount}元免`
          case '5':
            this.feeRuleValue = this.point_fee
            return `${this.point_fee}积分抵`
          case '6':
            this.feeRuleValue = this.cash_payment
            return `缴${this.cash_payment}元`
        }
      }
    },
    methods: {
      showPopup () {
        this.bankPopup = true
        this.getBankList()
      },
      closePopup () {
        this.bankPopup = false
      },
      showType () {
        if (this.bank_id === '' || this.bank_name === '') {
          msg('请先选择银行')
          return false
        }
        this.typePopup = true
      },
      closeType () {
        this.typePopup = false
      },
      showOwner () {
        this.ownerPopup = true
        this.getOwnerList()
      },
      closeOwner () {
        this.ownerPopup = false
      },
      showRule () {
        this.rulePopup = true
      },
      closeRule () {
        this.rulePopup = false
      },
      statementDate () {
        this.$refs.statement_day.open()
      },
      showPicker () {
        this.$refs.fee_date.open()
      },
      getBankList () {
        this.$post('/vue/bank/get_pinyin_list', {}).then((res) => {
          this.bankList = res
        })
      },
      getOwnerList () {
        this.$post('/vue/card/get_user_owners', '').then(data => {
          this.ownerList = data
        })
      },
      bankChoose (id, name) {
        this.bank_id = id
        this.bank_name = name
        this.getCardByBank()
        this.closePopup()
      },
      getCardByBank () {
        let params = {bank_id: this.bank_id}
        this.$post('/vue/card/get_cards_by_bank_id', params).then(data => {
          this.cardTypeList = data
        })
      },
      ownerChoose (id, name) {
        this.card_owner = name
        this.card_owner_id = id
        this.closeOwner()
      },
      cardChoose (id, name) {
        this.card_type = name
        let params = {card_id: id}
        this.$post('/vue/card/card_info', params).then(data => {
          this.payment_day = data.distance_to_billday
          // if (data.annual_fee_policy.includes('笔')) {
          //   this.feeRule = '3'
          //   let tmp = data.annual_fee_policy.substr(data.annual_fee_policy.indexOf('笔') - 1, 1)
          //   this.feeRuleValue = tmp
          //   this.swing_times = tmp
          // }
          this.closeType()
        })
      },
      saveCardType () {
        this.typePopup = false
      },
      radioFocus (f) {
        let iptObj = {1: 'inter_valid', 2: 'life_free', 3: 'swing_times', 4: 'consume_amount', 5: 'point_fee', 6: 'cash_payment'}
        for (let i in iptObj) {
          if (i === f) {
            continue
          }
        }
        this.feeRule = f
      },
      getCardInfo () {
        let params = {id: this.card_id}
        this.$post('/vue/card/card_edit', params).then(res => {
          this.bank_id = res.bank_id
          this.bank_name = res.bank_name
          this.card_type = res.card_type
          this.card_no = res.card_no
          this.card_owner = res.owners[res.owner]
          this.card_owner_id = res.owner
          this.credit_amount = res.credit_amount
          this.statement_day = res.statement_day
          this.statement_day_text = `每月${res.statement_day}日`
          this.payment_day = res.payment_day
          this.annual_fee_date = res.annual_fee_date
          let feeDate = res.annual_fee_date.split('/')
          this.annual_fee_date_text = `每年${feeDate[0]}月${feeDate[1]}日`
          this.feeRule = res.fee_rule
          this.feeRuleValue = res.fee_rule_value
          switch (this.feeRule) {
            case '3':
              this.swing_times = res.fee_rule_value
              break
            case '4':
              this.consume_amount = res.fee_rule_value
              break
            case '5':
              this.point_fee = res.fee_rule_value
              break
            case '6':
              this.cash_payment = res.fee_rule_value
              break
          }
        })
      },
      save () {
        if (this.bank_id === '' || this.bank_name === '') {
          msg('请选择银行')
          return false
        }
        if (this.card_type === '') {
          msg('请填写卡种')
          return false
        }
        if (this.card_type.length > 5) {
          msg('卡种不能超过五位')
          return false
        }
        if (this.card_no === '') {
          msg('请填写卡号后四位')
          return false
        }
        if (isNaN(Number(this.card_no))) {
          msg('卡号只能填写数字')
          return false
        }
        if (this.card_no.toString().length !== 4) {
          msg('卡号填写后四位即可')
          return false
        }
        if (this.credit_amount === '') {
          msg('请填写额度')
          return false
        }
        if (this.credit_amount > 5000000) {
          msg('额度不能超过500万')
          return false
        }
        if (this.statement_day === '') {
          msg('请填写销账单日')
          return false
        }
        if (this.payment_day === '') {
          msg('请填写距离还款的最大天数')
          return false
        }
        if (this.payment_day > 25) {
          msg('还款日-账单日不能超过25')
          return false
        }
        if (this.annual_fee_date === '') {
          msg('请选择年费日期')
          return false
        }
        if (this.inter_valid === '' &&
            this.life_free === '' &&
            this.swing_times === '' &&
            this.consume_amount === '' &&
            this.point_fee === '' &&
            this.cash_payment === '') {
          msg('请选择年费抵扣规则')
          return false
        }
        let params = {
          card_id: this.card_id,
          bank_id: this.bank_id,
          bank_name: this.bank_name,
          card_type: this.card_type,
          card_no: this.card_no,
          owner: this.card_owner_id,
          credit_amount: this.credit_amount,
          statement_day: this.statement_day,
          payment_day: this.payment_day,
          annual_fee_date: this.annual_fee_date,
          fee_rule: this.feeRule,
          fee_rule_value: this.feeRuleValue
        }
        // 请求
        this.$post('/vue/card/card_save', params).then(data => {
          if (parseInt(this.card_id) !== 0) {
            msg('卡片修改成功')
          } else {
            msg('卡片添加成功')
          }
          this.$router.go(-1)
        })
      },
      saveOwner () {
        if (this.ownerName.length > 3) {
          msg('持卡人不能超过三位')
          return false
        }
        let params = {owner: this.ownerName}
        this.$post('/vue/card/save_card_owner', params).then(data => {
          msg('添加成功')
          this.ownerName = ''
          this.getOwnerList()
        })
      },
      setOwner () {
        this.ownerTitle = '编辑持卡人'
        this.ifSet = true
      },
      deleteOwner (id) {
        let params = {id: id}
        this.$post('/vue/card/del_user_owner', params).then(data => {
          msg('删除成功')
          for (let i = 0; i < this.ownerList.length; i++) {
            if (Number(this.ownerList[i].id) === Number(id)) {
              this.ownerList.splice(i, 1)
            }
          }
        })
      },
      completeOwner () {
        this.ownerTitle = '选择持卡人'
        this.ifSet = false
      },
      saveCustom () {
        if (this.custom.length > 4) {
          msg('银行名称不能超过四位')
          return false
        }
        let params = {bank: this.custom}
        this.$post('/vue/bank/save_user_custom_bank', params).then(data => {
          msg('自定义银行保存成功')
          this.getBankList()
        })
      },
      setBank () {
        this.bankTitle = '编辑自定义银行'
        this.ifSet = true
      },
      completeBank () {
        this.bankTitle = '选择银行'
        this.ifSet = false
      },
      deleteBank (id) {
        let params = {id: id}
        MessageBox.confirm('与该银行相关的卡片同时会被删除', '确认删除银行吗？').then(action => {
          if (action === 'confirm') {
            this.$post('/vue/bank/del_user_customer_bank', params).then(data => {
              msg('删除成功')
              this.getBankList()
            })
          }
        })
      },
      // 销账单提示
      billAlert () {
        let alertContent = `
          <p>当日18:00还款，本期可0️账单</p>
          <p>交行、招行为账单日前一天</p>
          <p>其他大部分银行为账单日当天</p>
          `
        MessageBox.alert(alertContent, '温馨提示', {closeOnClickModal: true})
      },
      // 最长还款日提示
      repayAlert () {
        let alertContent = `
          <p>账单出来后，多少天后是还款日！</p>
          `
        MessageBox.alert(alertContent, '温馨提示', {closeOnClickModal: true})
      },
      // 年费缴纳日提示
      feeAlert () {
        let alertContent = `
          <p>每张卡片的年费日和规则都不相同！</p>
          <p>建议电话银行了解清楚！</p>
          `
        MessageBox.alert(alertContent, '温馨提示', {closeOnClickModal: true})
      },
      inArray (arr, val) {
        for (let i = 0; i < arr.length; i++) {
          if (val === arr[i]) {
            return i
          }
        }
        return false
      }
    },
    mounted () {
      // 判断是否为修改卡片
      if (parseInt(this.card_id) !== 0) {
        this.getCardInfo()
      }
    }
  }
  const msg = (msg) => {
    Toast({
      message: msg,
      position: 'bottom',
      className: 'pop-in-toast',
      duration: 2000
    })
  }
</script>

<style lang="less">
  @c-124: rgb(124, 124, 124);
  @c-169: rgb(169, 169, 169);
  @c-226: rgb(226, 226, 226);
  @c-235: rgb(235, 235, 235);
  @c-blue: rgb(108, 184, 222);
  @c-light-blue: rgb(240, 244, 247);
  @c-dark-blue: rgb(40, 100, 150);

  .card-add {
    background-color: @c-light-blue;
    height: calc(~'100vh - 56px');
    overflow-x: hidden;
    overflow-y: scroll;
    .pos-r {
      position: relative;
      .helper {
        width: 24px;
        height: 24px;
        position: absolute;
        top: 12px;
        left: 108px;
      }
    }
    footer {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 2;
      background-color: #FFF;
      .mint-button {
        height: 40px;
        padding: 7px 0;
        margin: 8px;
        width: 168px;
        text-align: center;
        background-color: #6cb8de;
        border-radius: 20px;
        .mint-button-text {
          font-size: 13px;
          line-height: 24px;
          color: #FFF;
        }
      }
    }
    .mint-cell {
      min-height: 48px;
      margin: 16px 12px;
      color: @c-124;
      border-radius: 24px;
      box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.2);
      .mint-cell-wrapper {
        font-size: 12px;
        padding: 0 16px;
        text-align: left;
        background-size: 100% 0px;
        .mint-cell-title {
          .mint-cell-text {
            line-height: 24px;
          }
        }
        .mint-cell-value {
          .mint-field-core {
            color: @c-blue;
          }
          .mint-field-other {
            img {
              width: 24px;
              height: 24px;;
              &.big {
                width: 48px;
                height: 48px;
                margin-right: -16px;
              }
            }
          }
        }
      }
    }
    .mint-popup-right {
      width: 82vw;
      height: 100vh;
      text-align: left;
      overflow-x: hidden;
      overflow-y: scroll;
      img {
        width: 24px;
        height: 24px;
      }
      .title {
        padding: 12px;
        font-size: 15px;
        font-weight: bold;
        line-height: 24px;
        color: @c-124;
        img {
          float: right;
        }
        .blue-text {
          float: right;
          font-size: 13px;
          line-height: 24px;
          color: @c-blue;
        }
      }
      .block {
        .letter {
          height: 24px;
          padding: 0 12px;
          font-size: 12px;
          line-height: 24px;
          background-color: rgb(240, 244, 247);
          &.hide {
            display: none;
          }
        }
        .flex-box {
          padding: 12px 12px 0;
          display: flex;
          flex-wrap: wrap;
          align-items: flex-start;
          align-content: flex-start;
          justify-content: space-between;
          &.pd-0 {
            padding: 0;
          }
          .item {
            width: 88px;
            margin-bottom: 12px;
            text-align: center;
            font-size: 13px;
            line-height: 24px;
            color: @c-124;
            flex: 0 0 auto;
            border-radius: 4px;
            background-color: rgb(242, 247, 250);
            box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.15);
            position: relative;
            &.active {
              background-color: rgba(108, 184, 222, 0.3);
              color: @c-dark-blue;
              box-shadow: none;
            }
            &.other {
              position: absolute;
              right: 12px;
              top: 12px;
            }
            .delete {
              width: 24px;
              height: 24px;
              display: none;
              position: absolute;
              top: -12px;
              right: -12px;
            }
            &.edit {
              .delete {
                display: block;
              }
            }
          }
        }
      }
    }
    .mint-radiolist {
      // border-top: 1px solid #eee;
      .mint-radiolist-title {
        background: #FFF;
        margin: 0;
        padding: 0 12px;
        text-align: left;
      }
      .mint-cell {
        min-height: auto;
        padding: 12px;
        margin: 0;
        border-radius: 0;
        box-shadow: none;
        border-bottom: 1px solid @c-226;
        .mint-cell-wrapper {
          padding: 0;
          .mint-cell-title {
            .mint-radiolist-label {
              padding: 0;
              .mint-radio-label {
                margin: 0;
                font-size: 13px;
                line-height: 24px;
                color: @c-124;
              }
            }
          }
        }
      }
    }
    .radio-input-row {
      position: absolute;
      bottom: 0;
      width: 50%;
      left: 30%;
      overflow: hidden;
      .radio-input {
        width: auto;
        display: block;
        font-size: 12px;
        line-height: 20px;
        padding: 12px;
        margin-top: 3px;
        margin-bottom: 2px;
        float: left;
      }
    }
    .only-day {
      .mint-datetime-picker {
        .picker-items {
          .picker-slot:nth-child(1),
          .picker-slot:nth-child(2) {
            display: none;
          }
        }
      }
    }
    .month-day {
      .mint-datetime-picker {
        .picker-items {
          .picker-slot:nth-child(1){
            display: none;
          }
        }
      }
    }
  }
  .pop-in-toast, .mint-toast {
    z-index: 2500;
  }
</style>